package api.cie.rss;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import api.cie.rss.R;

import api.cie.rss.adapters.RSSListAdapter;
import api.cie.rss.common.Article;
import api.cie.rss.common.Category;
import api.cie.rss.common.RSS;
import api.cie.rss.dal.ArticleDAL;
import api.cie.rss.dal.DatabaseAdapter;
import api.cie.rss.dal.RSS_CategoryDAL;
import api.cie.rss.dal.RssDAL;
import api.cie.rss.utils.ParserTools;
import api.cie.rss.utils.Utils;

public class AddFluxActivity extends Activity implements View.OnClickListener{
	
	private List<RSS> listRSS;
	private Button cancel;
	private Button addFlux;
	private DatabaseAdapter dbAdapter;

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_add_flux);
        dbAdapter = new DatabaseAdapter(this);
        String url = getIntent().getExtras().getString("url");
        
        listRSS = ParserTools.getRSS(url);
        
        RSSListAdapter rssListAdapter = new RSSListAdapter(this, listRSS);
        
        ListView list = (ListView)findViewById(R.id.listFluxAdd);
        list.setAdapter(rssListAdapter); 
        
        cancel = (Button)findViewById(R.id.btnCancel);
        cancel.setOnClickListener(this);
        
        addFlux = (Button)findViewById(R.id.btnAddFlux);
        addFlux.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		if(view == cancel){
			Intent intent = new Intent(this, FluxListActivity.class);
			startActivity(intent);
		}
		else if(view == addFlux){
			dbAdapter.open();
			 RssDAL rssDAL = new RssDAL(dbAdapter);
			 ArticleDAL articleDAL = new ArticleDAL(dbAdapter);
			 RSS_CategoryDAL rss_categoryDAL = new RSS_CategoryDAL(dbAdapter);

			// Insert the new RSSs into the database
			 for(RSS rss : listRSS){
				 if(rss.ischecked){
					 int idRss = (int)rssDAL.createRSS(rss.getTitle(), rss.getUrl(), 1);				 
					 List<Article> articleRSS = ParserTools.getArticles(rss.getUrl());
					// Insert the new articles into the database
	                 for(Article a:articleRSS) {
	                         articleDAL.createArticle(a.getTitle(), a.getDescription(), rss.getUrl(),
	                                        idRss, a.getRating(), Utils.dateToString(a.getPublishingDate()));
	                 }
	                 for(Category cat: rss.getCategories()){
	                	 rss_categoryDAL.createRSSCategory(idRss, cat.getId());
	                 }
				 }	

			 }
			 dbAdapter.close();
			 Intent intent = new Intent(this, FluxListActivity.class);
			 startActivity(intent);
		}
	}

}
